//
//  DrawingView.m
//  Objective-C
//
//  Created by S_Line on 2018/7/4.
//  Copyright © 2018年 S_Line. All rights reserved.
//

#import "DrawingView.h"

#define  BRUSH_SIZE 16.0

@interface DrawingView()

@property (nonatomic, strong) NSMutableArray *strokes;

@end

@implementation DrawingView

- (void)awakeFromNib {
    [super awakeFromNib];
    // create array
    self.strokes = [NSMutableArray new];
    self.layer.drawsAsynchronously = true;
}

- (instancetype)init {
    self = [super init];
    
    if (self) {
        // create array
        self.strokes = [NSMutableArray new];
        self.layer.drawsAsynchronously = true;
    }
    
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    
    if (self) {
        // create array
        self.strokes = [NSMutableArray new];
        self.layer.drawsAsynchronously = true;
    }
    
    return self;
}

- (void)addBrushStrokeAtPoint:(CGPoint)point {
    // add brush stroke to array
    [self.strokes addObject:[NSValue valueWithCGPoint:point]];
    
    // needs redraw
//    [self setNeedsDisplay];
    
    // set dirty rect
    [self setNeedsDisplayInRect:[self brushRectForPoint:point]];
}

- (CGRect)brushRectForPoint:(CGPoint)point {
    return CGRectMake(point.x - BRUSH_SIZE / 2.0, point.y - BRUSH_SIZE / 2.0, BRUSH_SIZE, BRUSH_SIZE);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // get the starting point
    CGPoint point = [[touches anyObject] locationInView:self];
    
    // add brush stroke
    [self addBrushStrokeAtPoint:point];
}

- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // get the current point
    CGPoint point = [[touches anyObject] locationInView:self];
    
    // add brush stroke
    [self addBrushStrokeAtPoint:point];
}

- (void)drawRect:(CGRect)rect {
    // redraw strokes
    for (NSValue *value in self.strokes) {
        // get point
        CGPoint point = [value CGPointValue];
        
        // get brush rect
        CGRect brushRect = CGRectMake(point.x - BRUSH_SIZE / 2.0, point.y - BRUSH_SIZE / 2.0, BRUSH_SIZE, BRUSH_SIZE);
        
        // draw brush stroke
//        [[UIImage imageNamed:@"caBrush"] drawInRect:brushRect];
        
        // only draw brush stroke if it intersects dirty rect
        if (CGRectIntersectsRect(rect, brushRect)) {
            [[UIImage imageNamed:@"caBrush"] drawInRect:brushRect];
        }
    }
}

@end
